package com.wangxinenpu.springbootdemo.config.security;

import com.wangxinenpu.springbootdemo.dataobject.model.LoginUser;
import com.wangxinenpu.springbootdemo.dataobject.model.SysUser;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String name = authentication.getName();
        String password = authentication.getCredentials().toString();

        if (shouldAuthenticateUser(name, password)) {
            LoginUser loginUser=new LoginUser();
            SysUser sysUser=new SysUser();
            sysUser.setUserName(name);
            loginUser.setUser(sysUser);
            return new UsernamePasswordAuthenticationToken(loginUser, password, new ArrayList<>());
        } else {
            throw new BadCredentialsException("External system authentication failed");
        }
    }

    private boolean shouldAuthenticateUser(String name, String password) {
        // 这里进行你的验证逻辑，比如查询数据库，比较用户名密码等等
        return true;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
